import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getBanners, getBannerById, createBanner, updateBanner, deleteBanner } from '@/api/banner'

export const useBannerStore = defineStore('banner', () => {
  const banners = ref<any[]>([])
  const loading = ref(false)

  // 获取所有轮播图
  const fetchBanners = async () => {
    try {
      loading.value = true
      const response = await getBanners()
      console.log('轮播图API响应:', response)
      if (response.data && response.data.success && response.data.banners) {
        banners.value = response.data.banners
      }
      return response.data
    } catch (error: any) {
      console.error('获取轮播图失败:', error)
      return { success: false, message: error.response?.data?.message || '获取轮播图失败' }
    } finally {
      loading.value = false
    }
  }

  // 根据ID获取轮播图
  const fetchBannerById = async (id: number) => {
    try {
      loading.value = true
      const response = await getBannerById(id)
      if (response.data && response.data.success) {
        return response.data.banner
      }
      return null
    } catch (error: any) {
      console.error('获取轮播图详情失败:', error)
      return null
    } finally {
      loading.value = false
    }
  }

  // 创建轮播图
  const addBanner = async (bannerData: any) => {
    try {
      loading.value = true
      const response = await createBanner(bannerData)
      if (response.data && response.data.success) {
        // 重新获取轮播图列表
        await fetchBanners()
      }
      return response.data
    } catch (error: any) {
      console.error('创建轮播图失败:', error)
      return { success: false, message: error.response?.data?.message || '创建轮播图失败' }
    } finally {
      loading.value = false
    }
  }

  // 更新轮播图
  const editBanner = async (id: number, bannerData: any) => {
    try {
      loading.value = true
      const response = await updateBanner(id, bannerData)
      if (response.data && response.data.success) {
        // 重新获取轮播图列表
        await fetchBanners()
      }
      return response.data
    } catch (error: any) {
      console.error('更新轮播图失败:', error)
      return { success: false, message: error.response?.data?.message || '更新轮播图失败' }
    } finally {
      loading.value = false
    }
  }

  // 删除轮播图
  const removeBanner = async (id: number) => {
    try {
      loading.value = true
      const response = await deleteBanner(id)
      if (response.data && response.data.success) {
        // 重新获取轮播图列表
        await fetchBanners()
      }
      return response.data
    } catch (error: any) {
      console.error('删除轮播图失败:', error)
      return { success: false, message: error.response?.data?.message || '删除轮播图失败' }
    } finally {
      loading.value = false
    }
  }

  return {
    banners,
    loading,
    fetchBanners,
    fetchBannerById,
    addBanner,
    editBanner,
    removeBanner
  }
}) 